package demo3;

import demo2.Util;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class Test {
    public static void main(String[] args) {
        JedisPool pool= Util.getInstance();
        Jedis j=pool.getResource();
        j.set("count","10");
        j.ltrim("orders",-1,0);//清空消息队列

        for(int i=0;i<100;i++){
            new Thread(i+"号"){
                public void run(){
                    Jedis j=null;
                    try {
                        j=pool.getResource();
                        long count = Long.valueOf(j.get("count"));
                        if (count <= 0) {
                            System.out.println("没有商品了，结束购物!");
                            return;
                        }
                        //下面可能超卖
                        count = j.decr("count");//原子操作
                        if (count >= 0) {
                            j.rpush("orders", Thread.currentThread().getName());
                        } else {
                            System.out.println("xxxxxxxxxxxxxxxx虽然成功减了库存，但仍然失败!xxxxxxxxxxxxxxxx");
                        }
                    }finally {
                        Util.release(pool,j);
                    }
                }
            }.start();
        }
        System.out.println("==============="+j.lrange("orders",0,-1)+"================");
    }
}
